package io.github.hadyang.leetcode.offer;

import java.util.LinkedList;
import org.junit.Test;

/** @author haoyang.shi */
public class MinStack {

  @Test
  public void test() {
    MinStack minStack = new MinStack();

    System.out.println(minStack.min());
    System.out.println(minStack.top());
    minStack.pop();
    minStack.push(1);
    minStack.push(-1);
    System.out.println(minStack.min());
    System.out.println(minStack.top());

    minStack.pop();
    System.out.println(minStack.min());
  }

  private LinkedList<Integer> stack = new LinkedList<>();
  private LinkedList<Integer> min = new LinkedList<>();

  public void push(int node) {
    stack.addLast(node);

    if (min.isEmpty()) {
      min.addLast(node);
      return;
    }

    if (node < min.peekLast()) {
      min.addLast(node);
    } else {
      min.addLast(min.peekLast());
    }
  }

  public void pop() {
    if (stack.isEmpty()) {
      return;
    }

    stack.removeLast();
    min.removeLast();
  }

  public int top() {
    if (stack.peekLast() == null) {
      return 0;
    }

    return stack.peekLast();
  }

  public int min() {
    if (min.peekLast() == null) {
      return 0;
    }

    return min.peekLast();
  }
}
